<template>
  <div class="app-container">
    <el-form ref="form" :model="book" label-width="120px">
      <el-form-item label="名称">
        <el-input v-model="book.title"/>
      </el-form-item>
      <el-form-item label="类别">
        <el-tag
          v-for="tag in book.category"
          :key="tag"
          :disable-transitions="false"
          closable
          @close="handleClose(tag)">
          {{ tag.value }}
        </el-tag>
        <el-input
          v-if="inputVisible"
          ref="saveTagInput"
          v-model="inputValue"
          class="input-new-tag"
          size="small"
          @blur="handleInputConfirm"
          @keyup.enter.native="handleInputConfirm"
        >
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
      </el-form-item>

      <el-form-item label="书架位置">
        <el-input v-model="book.bookshelfLocation" type="text"/>
      </el-form-item>

      <el-form-item label="数量">
        <el-input-number v-model="book.count" :max="10" :min="1" label="描述文字"
                         @change="handleChange"></el-input-number>
      </el-form-item>


      <el-form-item label="内容">
        <el-input v-model="book.body" type="textarea"/>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-plus" type="primary" @click="onSubmit">添加/更新</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
//添加图书组件
export default {
  name: 'AddOrUpdateBook',
  data() {
    return {
      book: {
        title: '',
        body: '',
        category: [],
        bookshelfLocation: '',
        count: 0
      },
      inputVisible: false,
      inputValue: '',
    }
  },
  mounted() {
    if (this.$route.params.index) {
      let index = this.$route.params.index
      let book = this.$store.getters.updateBook(index)
      this.book = book
    }
  },
  methods: {
    onSubmit() {
      this.$message('submit!')
    },
    onCancel() {
      this.$message({
        message: 'cancel!',
        type: 'warning'
      })
    },
    handleClose(tag) {
      this.book.category.splice(this.book.category.indexOf(tag), 1);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.book.category.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    handleChange(value) {
      console.log(value);
    }
  }
}
</script>

<style scoped>
.line {
  text-align: center;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>

